package com.mo2323.merchant.secruity.auth;

import com.alibaba.dubbo.config.annotation.Reference;
import com.mo2323.common.VO;
import com.mo2323.common.util.AjaxObject;
import com.mo2323.service.merchant.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 28876
 */
@RestController
public class AuthController {
    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;
    @Reference
    private IUserService userService;

    @RequestMapping(value = "auth", method = {RequestMethod.POST, RequestMethod.POST})
    @ResponseBody
    public AjaxObject createAuthenticationToken(String userName, String password) throws AuthenticationException {
        try{
            VO vo = userService.getUserInfo(userName, password);
            final String token = authService.login(userName, password);
            return AjaxObject.ok()
                    .put("data", vo.toHashMap(true))
                    .put("token", token);
        } catch (Exception e){
            return AjaxObject.error(e.getMessage());
        }
    }

    @RequestMapping(value = "refresh", method = {RequestMethod.POST, RequestMethod.POST})
    @ResponseBody
    public AjaxObject refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        if (refreshedToken == null) {
            return AjaxObject.error("刷新Token失败: 未授权");
        } else {
            VO vo = new VO();
            vo.set("token", refreshedToken);
            return AjaxObject.ok().put("data", vo.toHashMap(true));
        }
    }
}
